<!--
 * @Author: shenya
 * @Date: 2023-11-01 10:48:25
 * @Description: 新增组件
-->
<template>
  <el-dialog
    :title="action === 'add' ? '新增' : '编辑'"
    :visible.sync="visible"
    width="50%"
    append-to-body
  >
    <el-form
      ref="ruleForm"
      :model="ruleForm"
      :rules="rules"
      label-width="100px"
      class="demo-ruleForm"
    >
      <el-form-item
        label="页面名称："
        prop="pageName"
      >
        <el-input
          v-model.trim="ruleForm.pageName"
          maxlength="20"
          show-word-limit
        ></el-input>
      </el-form-item>
      <div
        v-for="(item, index) in pageList"
        :key="index"
        class="app"
      >
        <div class="app-title">{{ item.title }}</div>
        <div class="app-content">
          <el-form-item
            label="路由："
            :prop="item.route"
          >
            <el-input
              v-model="item.route"
              maxlength="100"
              show-word-limit
            ></el-input>
          </el-form-item>
          <avue-crud
            ref="crud"
            v-model="form"
            :option="accountOption"
            :data="item.data"
          >
            <template #menu="{ row }">
              <el-button
                v-if="row.$index !== 0"
                type="text"
                @click="deleteRow(item.tabIndex, row.$index)"
              >
                删除
              </el-button>
            </template>
          </avue-crud>
        </div>
      </div>
    </el-form>
    <div style="margin-top: 20px">
      <avue-form
        ref="crud"
        v-model="addform"
        :option="uploadOption"
        :upload-before="uploadBefore"
        :upload-change="$uploadChange"
        :upload-error="uploadError"
      ></avue-form>
    </div>
    <template #footer>
      <el-button
        type="primary"
        :loading="loading"
        @click="submit"
      >
        保存
      </el-button>
      <el-button @click="visible = false">取消</el-button>
    </template>
  </el-dialog>
</template>
<script>
import {
  insertPage,
  selectPageById,
  updatePage,
} from '@/api/operation/advertising';
import { accountOption, uploadOption } from '@/const/crud/advertising/page';
export default {
  props: {
    value: {
      type: Boolean,
      default: false,
    },
    action: {
      type: String,
    },
    id: {
      type: String,
    },
  },
  data() {
    return {
      pageList: [
        {
          title: 'APP页面',
          route: '',
          data: [
            {
              id: 0,
              index: 0,
              $cellEdit: true,
              parameter: '',
              parameterName: '',
            },
          ],
        },
        {
          title: '小程序页面',
          route: '',
          data: [
            {
              id: 1,
              index: 1,
              $cellEdit: true,
              parameter: '',
              parameterName: '',
            },
          ],
        },
      ],
      uploadOption: uploadOption(),
      accountOption: accountOption(),
      ruleForm: {},
      addform: {},
      form: {},
      rules: {
        pageName: [
          { required: true, message: '请输入页面名称', trigger: 'blur' },
        ],
      },

      loading: false,
    };
  },
  computed: {
    visible: {
      get() {
        return this.value;
      },
      set(val) {
        this.$emit('input', val);
      },
    },
  },
  watch: {
    visible(val) {
      if (!val) {
        this.$refs.ruleForm.resetFields();
        this.$refs.crud.resetFields();
        this.pageList = [
          {
            title: 'APP页面',
            route: '',
            data: [
              {
                id: 0,
                index: 0,
                $cellEdit: true,
                parameter: '',
                parameterName: '',
              },
            ],
          },
          {
            title: '小程序页面',
            route: '',
            data: [
              {
                id: 1,
                index: 1,
                $cellEdit: true,
                parameter: '',
                parameterName: '',
              },
            ],
          },
        ];
      } else {
        this.pageList.forEach((item, index) => {
          item.tabIndex = index;
        });
        if (this.action === 'edit') {
          selectPageById(this.id).then((res) => {
            this.ruleForm = res.data.data;
            // this.ruleForm.pageAddress = [this.ruleForm.pageAddress];
            this.addform.pageAddress = [this.ruleForm.pageAddress];
            //app
            this.pageList[0].route = this.ruleForm.appRouter;
            this.pageList[0].data = JSON.parse(this.ruleForm.appParams);
            //小程序
            this.pageList[1].route = this.ruleForm.mpRouter;
            this.pageList[1].data = JSON.parse(this.ruleForm.mpParams);
            this.pageList[0].data.forEach((item) => {
              item.$cellEdit = true;
            });
            this.pageList[1].data.forEach((item) => {
              item.$cellEdit = true;
            });
          });
        }
      }
    },
  },
  created() {},
  methods: {
    async uploadBefore(file, done, loading, column) {
      const isType =
        file.type === 'image/png' ||
        file.type === 'image/jpg' ||
        file.type === 'image/jpeg';
      if (!isType) {
        loading();
        this.$message.error('仅支持上传JPG、PNG格式图片!');
        return;
      }
      done();
    },
    //删除行
    deleteRow(tabIndex, rowIndex) {
      console.log('tabIndx', tabIndex);
      const data = this.pageList[tabIndex].data;
      data.splice(rowIndex, 1);
    },
    //提交
    submit() {
      this.$refs.ruleForm.validate(async (valid, done) => {
        if (valid) {
          if (this.action === 'add') {
            console.log('this.pageList[1].data', this.pageList[1].data);

            const app = JSON.stringify(
              this.pageList[0].data.map((item) => {
                return {
                  parameter: item.parameter,
                  parameterName: item.parameterName,
                };
              })
            );
            const applet = JSON.stringify(
              this.pageList[1].data.map((item) => {
                return {
                  parameter: item.parameter,
                  parameterName: item.parameterName,
                };
              })
            );
            console.log('applet', applet);
            const params = {
              pageName: this.ruleForm.pageName,
              appParams: app,
              appRouter: this.pageList[0].route,
              mpRouter: this.pageList[1].route,
              mpParams: applet,
              pageAddress: this.addform.pageAddress,
            };
            console.log('params', params);
            this.loading = true;
            insertPage(params)
              .then((res) => {
                this.$emit('refresh');
                this.visible = false;
                this.loading = false;
                this.$message.success('新增成功！');
                done();
              })
              .catch((err) => {
                this.loading = false;
                done();
                throw new Error(err);
              });
          } else {
            this.loading = true;
            const appName = JSON.stringify(this.pageList[0].data);
            const appletName = JSON.stringify(this.pageList[1].data);
            const params = {
              id: this.id,
              pageName: this.ruleForm.pageName,
              appParams: appName,
              mpParams: appletName,
              appRouter: this.pageList[0].route,
              mpRouter: this.pageList[1].route,
              pageAddress: this.addform.pageAddress,
            };
            console.log('papap', params);
            updatePage(params)
              .then((res) => {
                this.$emit('refresh');
                this.visible = false;
                this.loading = false;
                this.$message.success('编辑成功！');
                done();
              })
              .catch((err) => {
                done();
                this.loading = false;
                throw new Error(err);
              });
          }
        }
      });
    },
    uploadError(error, column) {
      if (error === '文件太大不符合') {
        this.$message.warning(`文件大小不能超过${column.fileSize / 1024}M`);
      }
    },
  },
};
</script>
<style lang="scss" scoped>
.app {
  margin-bottom: 20px;
  .app-title {
    border-bottom: 1px solid #dcdfe6;
    padding-bottom: 15px;
    font-weight: 600;
  }
  .app-content {
    margin-top: 25px;
  }
}
</style>
